<template>
  <div></div>
</template>
<script lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  defineComponent,
} from "vue";
import bus from "@/utils/bus";
import socket from "./socket.js";

export default defineComponent({
  setup() {
    onMounted(() => {
      //
      window.addEventListener("receive", getServerInfo);
      window.addEventListener("connectStatus", getConnectStatus);
      connect();
    });

    const connect = () => {
      socket.connectWebsocket();
    };
    const closeConnect = () => {
      if (socket.isConnection()) socket.closeWebSocket();
    };
    const send = () => {
      socket.webSocketSend();
    };

    const getServerInfo = (res) => {
      let data = JSON.parse(res.detail)
      switch(data.type){
        case 'FarmRecord' :
          bus.emit("FarmRecordUpdate", data);
          break;
        case 'Crop' :
          bus.emit("CropUpdate", JSON.parse(data.msg));
          break;
        default :
          break;
      }
    };
    const getConnectStatus = (res) => {
      //
    };

    onBeforeUnmount(() => {
      closeConnect();
      if (socket.isConnection()) {
        window.removeEventListener("receive", getServerInfo);
        window.removeEventListener("connectStatus", getConnectStatus);
      }
    });

    return{
      
    }
  },
});
</script>
<style lang="scss" scoped>
</style>